import 'dart:ui' as ui;

import 'package:decimal/decimal.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/utils/text_input_format_utils.dart';
import 'package:kq_flutter_pad_widgets/resources/kq_pad_theme_colors.dart';
import 'package:kq_flutter_pad_widgets/widgets/textFiled/kq_pad_textfiled.dart';

import '../../resources/l10n/kq_pad_intl.dart';

/// 注塑机多段温度
class KqPadImmTemperatureView extends StatefulWidget {
  const KqPadImmTemperatureView(
      {super.key,
      this.data,
      this.isRedMarked,
      this.isCanEdit = false,
      this.paintShaderColors,
      this.valueCallback});

  /// 用逗号隔开的熔体温度
  final String? data;

  /// 颜色:0:KqPadThemeColors.text26 1:KqPadThemeColors.bgRed
  final String? isRedMarked;

  /// 是否可编辑吗
  final bool isCanEdit;

  final List<Color>? paintShaderColors;

  final void Function(String data)? valueCallback;

  @override
  State<StatefulWidget> createState() => KqPadImmTemperatureViewState();
}

class KqPadImmTemperatureViewState extends State<KqPadImmTemperatureView> {
  List<String> value = ['-'];
  List<String> colorArr = ['0'];

  @override
  void initState() {
    super.initState();
    if (widget.data != null) {
      value = widget.data!.split(',');
    }
    if (widget.isRedMarked != null) {
      colorArr = widget.isRedMarked!.split(',');
    }
  }

  @override
  void didUpdateWidget(covariant KqPadImmTemperatureView oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.data != null) {
      value = widget.data!.split(',');
    } else {
      value = ['-'];
    }
    if (widget.isRedMarked != null) {
      colorArr = widget.isRedMarked!.split(',');
    } else {
      colorArr = ['0'];
    }
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      double width = constraints.maxWidth;
      double height = constraints.maxHeight;
      return SizedBox(
        width: width,
        height: height > 44.dm ? 44.dm : height,
        child: CustomPaint(
          painter: ImmTemperaturePainter(
              value: value,
              isCanEdit: widget.isCanEdit,
              isRedMarked: colorArr,
              paintShaderColors: widget.paintShaderColors),
          child: widget.isCanEdit
              ? Row(
                  children:
                      tempTextField(width, height > 44.dm ? 44.dm : height),
                )
              : null,
        ),
      );
    });
  }

  List<Widget> tempTextField(double maxWidth, double maxHeight) {
    List<Widget> widgets = [];
    // double temperaturePartWidth = (maxWidth - 42.dm) / (value.length) - 10.dm;
    double temperaturePartWidth =
        (maxWidth - 28.dm - 2.dm * (value.length + 1)) / (value.length) - 10.dm;
    for (var i = 0; i < value.length; i++) {
      Color color = colorArr.length > i && colorArr[i] == '1'
          ? KqPadThemeColors.textRed
          : KqPadThemeColors.text26;
      widgets.add(Container(
        margin: EdgeInsets.only(
          // left: i == 0 ? 20.dm + 2.dm + 5.dm : 2.dm + 5.dm * 2,
          left: i == 0 ? 20.dm + 2.dm + 5.dm : 2.dm + 10.dm,
          top: 10.dm,
        ),
        width: temperaturePartWidth,
        height: 14.dm,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Expanded(
              child: KqPadTextFiled(
                maxLines: 1,
                showShadow: false,
                useParentHeight: false,
                textColor: color,
                fontSize: 6.dm,
                textAlign: TextAlign.center,
                newValue: Decimal.tryParse(value[i])?.round().toString(),
                inputFormatters: [
                  FilteringTextInputFormatter.allow(RegExp("[0-9.]")),
                  FilteringTextInputFormatter.deny(RegExp(r'^\.+')), //不能小数点开头
                  NumLengthInputFormatter(integerLength: 9, decimalLength: 2),
                ],
                onChanged: (data) {
                  value.replaceRange(i, i + 1, [data]);
                  widget.valueCallback?.call(value.join(','));
                },
              ),
            ),
          ],
        ),
      ));
    }
    return widgets;
  }
}

class ImmTemperaturePainter extends CustomPainter {
  ImmTemperaturePainter(
      {required this.value,
      required this.isCanEdit,
      required this.isRedMarked,
      this.paintShaderColors});

  final List<String> value;

  final List<String> isRedMarked;

  final bool isCanEdit;

  final List<Color>? paintShaderColors;

  final Paint gradientPaint = Paint()..style = PaintingStyle.fill;
  final Paint whitePaint = Paint()
    ..style = PaintingStyle.fill
    ..color = Colors.white;

  @override
  void paint(Canvas canvas, Size size) {
    double width = size.width;
    double height = size.height;
    double temperaturePartWidth = (width - 28.dm - 2.dm * (value.length + 1)) /
        (value.length); // 每段温度的宽度(动态),高度写死
    List<double> temperaturePartCenterDxList = [];

    // 喷口
    Path path1 = Path();
    path1.moveTo(0, 19.dm);
    path1.lineTo(0, 35.dm);
    path1.lineTo(10.dm, 38.dm);
    path1.lineTo(20.dm, 38.dm);
    path1.lineTo(20.dm, 16.dm);
    path1.lineTo(10.dm, 16.dm);
    path1.close();
    _drawPathPart(canvas, Offset(0, 19.dm), Offset(20.dm, 38.dm), path1);

    // 温度段
    for (int i = 0; i < value.length; i++) {
      double startDx = 20.dm + (2.dm * (i + 1)) + (temperaturePartWidth * i);
      double endDx = startDx + temperaturePartWidth;
      Color color = isRedMarked.length > i && isRedMarked[i] == '1'
          ? KqPadThemeColors.textRed
          : KqPadThemeColors.text26;
      _drawTemperaturePart(canvas, Offset(startDx, 15.dm), Offset(endDx, 39.dm),
          value[i], color);
      temperaturePartCenterDxList.add(startDx + (temperaturePartWidth / 2));
    }

    // 尾部
    _drawRRectPart(
        canvas, Offset(width - 8.dm, 17.dm), Offset(width, 37.dm), 1.dm);

    // 加料口
    double lastTemperaturePartCenterDx =
        temperaturePartCenterDxList[value.length - 1];
    Path path2 = Path();
    path2.moveTo(lastTemperaturePartCenterDx - 12.dm, 4.dm);
    path2.lineTo(lastTemperaturePartCenterDx - 6.dm, 11.dm);
    path2.lineTo(lastTemperaturePartCenterDx - 6.dm, 15.dm);
    path2.lineTo(lastTemperaturePartCenterDx + 6.dm, 15.dm);
    path2.lineTo(lastTemperaturePartCenterDx + 6.dm, 11.dm);
    path2.lineTo(lastTemperaturePartCenterDx + 12.dm, 4.dm);
    path2.close();
    _drawPathPart(canvas, Offset(lastTemperaturePartCenterDx - 12.dm, 0),
        Offset(lastTemperaturePartCenterDx + 12.dm, 16.dm), path2);

    // 底部文本
    for (int i = 0; i < value.length; i++) {
      _drawBottomText(
          canvas,
          temperaturePartCenterDxList[i],
          height,
          (i + 1).toString() + KqPadIntl.currentResource.segment,
          temperaturePartWidth);
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }

  /// 绘制路径图块
  _drawPathPart(Canvas canvas, Offset from, Offset to, Path path) {
    _setPaintShader(gradientPaint, from, to);
    canvas.drawPath(path, gradientPaint);
  }

  /// 绘制矩形图块
  _drawRRectPart(Canvas canvas, Offset from, Offset to, double radius) {
    _setPaintShader(gradientPaint, from, to);
    canvas.drawRRect(
        RRect.fromRectAndRadius(
            Rect.fromPoints(from, to), Radius.circular(radius)),
        gradientPaint);
  }

  /// 绘制每段温度块
  _drawTemperaturePart(
      Canvas canvas, Offset from, Offset to, String text, Color color) {
    _setPaintShader(gradientPaint, from, to);
    canvas.drawRRect(
        RRect.fromRectAndRadius(
            Rect.fromPoints(from, to), Radius.circular(2.dm)),
        gradientPaint);
    canvas.drawRRect(
        RRect.fromRectAndRadius(
            Rect.fromPoints(Offset(from.dx + 5.dm, from.dy + 5.dm),
                Offset(to.dx - 5.dm, to.dy - 5.dm)),
            Radius.circular(1.dm)),
        whitePaint);
    if (!isCanEdit) {
      TextPainter textPainter = TextPainter(
          text: TextSpan(
              text: text.isNotEmpty
                  ? Decimal.tryParse(text)?.round().toString()
                  : '-',
              style: TextStyle(
                  fontSize: 6.dm, color: color, fontWeight: FontWeight.w500)),
          textDirection: TextDirection.ltr)
        ..layout(minWidth: 0, maxWidth: to.dx - from.dx - 12.dm);
      Offset center = Offset(
          from.dx + ((to.dx - from.dx) / 2), from.dy + ((to.dy - from.dy) / 2));
      Offset textStart = Offset(center.dx - (textPainter.size.width / 2),
          center.dy - (textPainter.size.height / 2));
      textPainter.paint(canvas, textStart);
    }
  }

  /// 绘制底部文本
  _drawBottomText(Canvas canvas, double centerDx, double parentHeight,
      String text, double maxWidth) {
    TextPainter textPainter = TextPainter(
        text: TextSpan(
            text: text,
            style: TextStyle(fontSize: 6.dm, color: const Color(0xFF262626))),
        textDirection: TextDirection.ltr)
      ..layout(minWidth: 0, maxWidth: maxWidth);
    Offset textStart = Offset(centerDx - (textPainter.size.width / 2),
        parentHeight - textPainter.size.height / 4);
    textPainter.paint(canvas, textStart);
  }

  /// 设置画笔shader
  _setPaintShader(Paint paint, Offset from, Offset to) {
    paint.shader = ui.Gradient.linear(
      from,
      Offset(from.dx, to.dy), // dx相同，渐变才会是垂直的
      paintShaderColors ??
          const <Color>[
            Color(0xFF68F2F3),
            Color(0xFF46BDBE),
            Color(0xFF3FA9AA),
          ],
      const <double>[0, 0.5, 1.0],
    );
  }
}
